package cn.tpshion.shop.common;

import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;

/**
 * 通用响应结果类
 *
 * @param <T> 响应数据的类型
 */
@Data
@JsonInclude(JsonInclude.Include.NON_NULL)
public class R<T> {

    /**
     * 状态码（200：成功，其他：失败）
     */
    private Integer code;

    /**
     * 提示信息，如果有错误时，前端可以获取该字段进行提示
     */
    private String msg;

    /**
     * 查询到的结果数据
     */
    private T data;

    private R() {

    }

    private R(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static <T> R<T> ok(T object) {
        R<T> r = new R<>();
        r.data = object;
        r.code = ResultCodeEnum.SUCCESS.getCode();
        r.msg = ResultCodeEnum.SUCCESS.getMessage();
        return r;
    }

    public static R<Void> ok() {
        R<Void> r = new R<>();
        r.code = ResultCodeEnum.SUCCESS.getCode();
        r.msg = ResultCodeEnum.SUCCESS.getMessage();
        return r;
    }

    public static R<Void> error(ResultCodeEnum resultCodeEnum) {
        R<Void> r = new R<>();
        r.code = resultCodeEnum.getCode();
        r.msg = resultCodeEnum.getMessage();
        return r;
    }

    public static R<Void> error(String msg) {
        R<Void> r = new R<>();
        r.code = ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode();
        r.msg = msg;
        return r;
    }

    public static <T> R<T> fail(String msg) {
        return new R(ResultCodeEnum.INTERNAL_SERVER_ERROR.getCode(), msg);
    }

    public static R<Void> error(ResultCodeEnum resultCodeEnum, String msg) {
        R<Void> r = new R<>();
        r.code = resultCodeEnum.getCode();
        r.msg = msg;
        return r;
    }
}
